<template>
  <div v-loading.fullscreen.lock="loading" :element-loading-text="$t('loading')" :class="['aui-wrapper',
  { 'aui-sidebar--fold': $store.state.sidebarFold }]">
    <template v-if="!loading">
      <main-navbar :openTheme="openTheme" :curModule="curModule" :moduleList="moduleList" :changeModule="changeModule" />
      <main-sidebar :curModule="curModule" />
      <div class="aui-content__wrapper">
        <!-- <template v-if="routeMeta.v2Flag">
          <MainContentV2 v-if="!$store.state.contentIsNeedRefresh" />
        </template>
        <template v-else>
          <MainContent v-if="!$store.state.contentIsNeedRefresh" />
        </template> -->
        <MainContent v-if="!$store.state.contentIsNeedRefresh" />
      </div>
      <main-theme-tools :isOpen="isOpen" :openTheme="openTheme" />
    </template>
    <update-password v-if="addOrUpdateVisible" ref="updatePassword"></update-password>
  </div>
</template>

<script>
import MainNavbar from './main-navbar'
import MainSidebar from './main-sidebar'
import MainContent from './main-content'
import MainContentV2 from './layout/v2/main-content'
import MainThemeTools from './main-theme-tools'
import UpdatePassword from './modules/user/update-password'
import debounce from 'lodash/debounce'
import { isEmpty } from '@/utils/validate'
import staticData from './main.json'

export default {
  provide () {
    return {
      // 刷新
      refresh () {
        this.$store.state.contentIsNeedRefresh = true
        this.$nextTick(() => {
          this.$store.state.contentIsNeedRefresh = false
        })
      }
    }
  },
  data () {
    return {
      loading: true,
      isOpen: false,
      curModule: {},
      moduleList: [],
      addOrUpdateVisible: false
    }
  },
  components: {
    MainNavbar,
    MainSidebar,
    MainContent,
    UpdatePassword,
    MainThemeTools,
    MainContentV2
  },
  watch: {
    $route: 'routeHandle'
  },
  computed: {
    routeMeta () {
      return this.$route.meta || {}
    }
  },
  created () {
    this.windowResizeHandle()
    this.routeHandle(this.$route)
    // MainThemeTools.methods.themeColorChangeHandle(MainThemeTools.data().themeColor)
    Promise.all([
      this.getUserInfo(),
      this.getPermissions(),
      this.getDictData(),
      this.getModuleList(),
      this.getUserPwdLevel(),
      this.$store.state.sidebarLayoutSkin = 'dark'
    ]).then(() => {
      this.loading = false
    })
  },
  methods: {
    // 窗口改变大小
    windowResizeHandle () {
      this.$store.state.sidebarFold = document.documentElement['clientWidth'] <= 992 || false
      window.addEventListener('resize', debounce(() => {
        this.$store.state.sidebarFold = document.documentElement['clientWidth'] <= 992 || false
      }, 1000))
    },
    // 路由, 监听
    routeHandle (route) {
      if (!route.meta.isTab) {
        return false
      }
      var tab = this.$store.state.contentTabs.filter(item => item.name === route.name)[0]
      if (!tab) {
        tab = {
          ...window.SITE_CONFIG['contentTabDefault'],
          ...route.meta,
          'name': route.name,
          'params': { ...route.params },
          'query': { ...route.query }
        }
        this.$store.state.contentTabs = this.$store.state.contentTabs.concat(tab)
      }
      this.$store.state.sidebarMenuActiveName = tab.menuId
      this.$store.state.contentTabsActiveName = tab.name
    },
    // 获取当前管理员信息
    getUserInfo () {
      return this.$http.get('/sys/user/info').then(({ data: res }) => {
        if (res.code !== 0) {
          return
        }
        this.$store.state.user = {
          ...this.$store.state.user,
          ...res.data
        }
      }).catch(() => {
      })
    },
    // 获取权限
    getPermissions () {
      return this.$http.get('/sys/menu/permissions').then(({ data: res }) => {
        if (res.code !== 0) {
          return
        }
        window.SITE_CONFIG['permissions'] = res.data
      }).catch(() => {
      })
    },
    // 加载字典数据
    getDictData () {
      return this.$http.get('/sys/sysdicttype/dictData').then(({ data: res }) => {
        window.SITE_CONFIG['dictData'] = res
      }).catch(() => {
      })
    },
    // 打开主题设置
    openTheme () {
      this.isOpen = !this.isOpen
    },
    // 设置当前模块
    changeModule (m) {
      this.curModule = m
      this.setStateCurModule(this.curModule)
      this.$cookies.set('curModuleId', m.id, { expires: 365 * 10 })
    },
    setStateCurModule (m) {
      this.$store.state.curModule = m
    },
    // 获取横幅模块相关数据
    getModuleList () {
      let menuList = window.SITE_CONFIG['menuList']
      this.moduleList = menuList.filter(item => item.type === staticData.typeModule)
      if (!isEmpty(this.moduleList) && this.moduleList.length > 0) {
        // 读取本地cookie
        let curModuleId = this.$cookies.get('curModuleId')
        let upModule = this.moduleList.filter(item => item.id === curModuleId)[0]
        if (!isEmpty(upModule)) {
          if (this.curModule !== upModule) this.curModule = upModule
          this.changeModule(upModule)
        } else {
          if (this.curModule !== this.moduleList[0]) this.curModule = this.moduleList[0]
          this.changeModule(this.moduleList[0])
        }
        this.setStateCurModule(this.curModule)
      }
    },
    // 获取用户密码等级
    getUserPwdLevel () {
      return this.$http.get('/user/center/userPwdLevel').then(({ data: res }) => {
        if (res.code !== 0) {
          return
        }
        // 判断是否开启初始密码提醒
        if (res.data.config.initPasswordModify !== 0) {
          // 判断是否是初始密码
          if (res.data.pwdLevel === 0) {
            this.openPassword(this.$t('updatePassword.pwdInit'), res.data.config.initPasswordModify)
            return null
          }
        }
        // 判断是否开启弱密码提醒
        if (res.data.config.passwordModify !== 0) {
          // 判断密码等级
          if (res.data.pwdLevel < res.data.config.passwordModifySecurityLevel) {
            this.openPassword(this.$t('updatePassword.pwdLevel'), res.data.config.passwordModify)
            return null
          }
          // 判断密码验证周期
          if (!res.data.pwdDate) {
            this.openPassword(this.$t('updatePassword.pwdUpdate'), res.data.config.passwordModify)
            return null
          }
        }
      }).catch(() => {
      })
    },
    // 打开密码提示窗口
    openPassword (message, modify) {
      this.$confirm(message, this.$t('prompt.title'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        showCancelButton: modify === 1,
        showClose: modify === 1,
        type: modify === 1 ? 'warning' : 'error'
      }).then(() => {
        this.updatePasswordHandle(modify)
      }).catch(() => {
      })
    },
    // 修改密码
    updatePasswordHandle (modify) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.updatePassword.showCancelButton = modify === 1
        this.$refs.updatePassword.init()
      })
    }
  }
}
</script>
